package com.cctc.security.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
public class UpLoadController {
	
	@RequestMapping("/demo/upload.html")
	public String  upload(){
		return  "/jsp/demo/UpLoad";
	}
	
	@RequestMapping("/activity/uploadImg.do")
	public void uploadImg(MultipartHttpServletRequest request, HttpServletResponse response) throws IOException {
		System.out.println(1);
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		SimpleDateFormat simpleFormat = new SimpleDateFormat("MMddHHmmsss");
		String generationfileName = simpleFormat.format(new Date()) + new Random().nextInt(1000);
		//保存路径
		String savePath = "D:/";
		String updateP = request.getParameter("updateP");
		String fileNameSuffix = null;
		String fileName = null;
		if (null != updateP && !"".equals(updateP)) {
			try {
				MultipartFile mf = request.getFile(updateP);
				fileName = mf.getOriginalFilename();
				if (null != mf && !"".equals(mf)) {
					fileNameSuffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
					SaveFileFromInputStream(mf.getInputStream(), savePath, generationfileName + "." + fileNameSuffix);
					out.write("{'state':'0','fileName':'" + generationfileName + "." + fileNameSuffix + "','updateP':'"
							+ updateP + "'}");
				}
			} catch (Exception e) {
				out.write("{'state':'1'}");
				e.printStackTrace();
			}
		}
	}

	//保存文件   1,文件   2，保存路径 3，文件名称
	public void SaveFileFromInputStream(InputStream stream, String path, String filename) throws IOException {
		FileOutputStream fs = new FileOutputStream(path + "/" + filename);
		byte[] buffer = new byte[1024 * 1024];
		//int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			//	bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}

}
